package com.hqyj.springboot.config.shiro;

import com.hqyj.springboot.modules.account.entity.Resource;
import com.hqyj.springboot.modules.account.entity.Role;
import com.hqyj.springboot.modules.account.entity.User;
import com.hqyj.springboot.modules.account.service.ResourceService;
import com.hqyj.springboot.modules.account.service.RoleService;
import com.hqyj.springboot.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.security.auth.login.AccountNotFoundException;
import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      //资源授权器
       SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();


        //从认证当中获取当前的信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        //从数据库查询当前用户的角色列表,并装载到资源授权器里
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(item -> {
           simpleAuthorizationInfo.addRole(item.getRoleName());
            // 再去查询每个角色的资源列表，并装载到资源授权器里
            List<Resource> resources = resourceService.getResourcesByRoleId(item.getId());
            resources.stream().forEach(it -> {
               simpleAuthorizationInfo.addStringPermission(it.getPermition());
            });
        });





        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取用户名
        String userName = (String) authenticationToken.getPrincipal();
        //通过用户名查找数据库的user信息
        User user = userService.getUserByUserName(userName);
        if (user == null){
            throw new UnknownAccountException("用户名不存在!");

        }
        //封装身份验证器
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());


    }
}
